package com.hjy.web.controller;


import com.hjy.from.UserLoginForm;
import com.hjy.from.UserRegisterForm;
import com.hjy.pojo.User;
import com.hjy.service.UserService;
import com.hjy.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import static com.hjy.consts.MallConst.*;
import static com.hjy.enums.ResponseEnum.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;


@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@GetMapping
	public ResponseVo<User> userInfo(HttpSession session){
		User user = (User)session.getAttribute(CURRENT_USER);
		if (user == null)
			return ResponseVo.error(NEED_LOGIN);

		return ResponseVo.success(user);
	}

	@PostMapping("/register")
	public ResponseVo<User> register(@Valid @RequestBody UserRegisterForm userForm,BindingResult bindingResult) {
		if (bindingResult.hasErrors()){
			log.error("注册提交的参数有误，{} {}",
					bindingResult.getFieldError().getField(),
					bindingResult.getFieldError().getDefaultMessage());
			return ResponseVo.error(PARAM_ERROR,bindingResult);
		}
		User user = new User();
		BeanUtils.copyProperties(userForm,user);
		return userService.register(user);
	}

	@PostMapping("/login")
	public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userLoginForm
			, BindingResult bindingResult, HttpSession session){

		if (bindingResult.hasErrors()){
			return ResponseVo.error(PARAM_ERROR,bindingResult);
		}
		ResponseVo<User> userResponseVo = userService.login(userLoginForm.getUsername(),userLoginForm.getPassword());

		//存入session
		session.setAttribute(CURRENT_USER,userResponseVo.getData());
		return userResponseVo;

	}

	@RequestMapping("/logout")
	public ResponseVo logout(HttpSession session){
		if(session.getAttribute(CURRENT_USER)==null)
			return ResponseVo.error(NEED_LOGIN);

		session.removeAttribute(CURRENT_USER);
		return ResponseVo.success();
	}

}
